# coding=utf-8
import socket
import time

import RPi.GPIO as GPIO

from config import Config
from infraredsensor import InfraredSensor
from lcdscreen import Screen
from microswitch import MicroSwith
from photoelectricsensor import PhotoElectricSensor
from stepper import Stepper


def Get_local_ip():
    """
    Returns the actual ip of the local machine.
    This code figures out what source address would be used if some traffic
    were to be sent out to some well known address on the Internet. In this
    case, a Google DNS server is used, but the specific address does not
    matter much. No traffic is actually sent.
    """
    try:
        csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        csock.connect(('123.125.115.110', 80))
        (addr, port) = csock.getsockname()
        csock.close()
        return addr
    except socket.error:
        return "127.0.0.1"


def initMotors():
    '''
    初始化电机
    :return:
    '''
    # 初始化MA电机
    ma_pulpin = int(Config().read("Stepper", "MA_pul_pin"))
    ma_dirpin = int(Config().read("Stepper", "MA_dir_pin"))
    ma_hz = int(Config().read("Stepper", "MA_hz"))
    mcx_dir = int(Config().read("Stepper", "MCX_REVERCE"))
    ma_stepper = Stepper(ma_pulpin, ma_dirpin, ma_hz, mcx_dir)
    ma_stepper.initMA()

    # 初始化MCX 电机
    mcx_pulpin = int(Config().read("Stepper", "MCX_pul_pin"))
    mcx_dirpin = int(Config().read("Stepper", "MCX_dir_pin"))
    mcx_hz = int(Config().read("Stepper", "MCX_hz"))
    mcx_dir = int(Config().read("Stepper", "MCX_REVERCE"))
    mcx_stepper = Stepper(mcx_pulpin, mcx_dirpin, mcx_hz, mcx_dir)
    mcx_stepper.initMCX()

    # 初始化MCY 电机
    mcy_pulpin = int(Config().read("Stepper", "MA_pul_pin"))
    mcy_pulpin = int(Config().read("Stepper", "MA_dir_pin"))
    mcy_hz = int(Config().read("Stepper", "MA_hz"))
    mcy_dir = int(Config().read("Stepper", "MCX_REVERCE"))
    mcy_stepper = Stepper(mcy_pulpin, mcy_pulpin, mcy_hz, mcy_dir)
    mcy_stepper.initMCY()


def initLock():
    '''
    初始化锁状态
    :return:
    '''
    gpio = Config().read("PhotoElectric", "SLK_pin")
    print(gpio)
    photoElectricSensor = PhotoElectricSensor(gpio)
    if photoElectricSensor.checkObstacle() != 1:  # 门未上锁
        screen.displayData("lock the door please")  # 显示数据


def initScreen():
    '''
    初始化屏幕
    :return:
    '''
    screen = Screen(bus=1, addr=0x27, cols=16, rows=2)
    ip = Get_local_ip()
    print(ip)
    screen.displayData(ip)  # 显示数据
    return screen


if __name__ == '__main__':
    try:

        screen = initScreen()
        print("初始化屏幕完成")
        time.sleep(4)  # 延迟4s

        initLock()
        print("初始化锁状态完成")
        time.sleep(0.5)  # 延迟500ms

        # 初始化电机
        initMotors()
        print("初始化电机状态完成")
        time.sleep(0.5)  # 延迟500ms

        while True:
            param = None
            while True:
                print("监听事件")
                # 微动开关01监听
                microSwith01 = MicroSwith(Config().read("MicroSwith", "MicroSwith_pin01"))
                if microSwith01.checkOnOrOff() == 1:  # 按下按键跳出控制
                    print("监听到按键01")
                    param = "01号开关被触发"
                    break
                time.sleep(0.1)  # 延迟100ms

                # 微动开关02监听
                microSwith02 = MicroSwith(Config().read("MicroSwith", "MicroSwith_pin02"))
                if microSwith02.checkOnOrOff() == 1:  # 按下按键跳出控制
                    print("监听到按键02")
                    param = "02号开关被触发"
                    break
                time.sleep(0.1)  # 延迟100ms

                # 红外开关监听
                infraredSensor = InfraredSensor(Config().read("Sys_Pins", "infraredSensor_pin"))
                if infraredSensor.checkObstacle() == 1:  # 有障碍物警告
                    print("监听到红外开关")
                    param = "红外开关监测有障碍物"
                    break
                time.sleep(0.1)  # 延迟100ms

                # 以下为自定义程序留白可以自行添加
            if param == "01号开关被触发":
                pass
            elif param == "02号开关被触发":
                pass
            elif param == "红外开关监测有障碍物":
                pass
            else:
                pass

    except KeyboardInterrupt:
        GPIO.cleanup()
